package com.school.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.school.demo.model.auto.User;
import com.school.demo.mapper.auto.UserMapper;
import com.school.demo.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author Charlotte
 * @since 2021-03-01
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public User findByPhone(String phone) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getMobile,phone);
        return this.getOne(queryWrapper);
    }

    @Override
    public Map<String,Object> login(Map<String, Object> map) {
        String code = "-1";
        Map<String,Object> res = new HashMap<>();
        String username = (String) map.get("username");
        String password = (String) map.get("password");

        User user = findByPhone(username);
        if (user == null){
            res.put("code",101);
            res.put("masg","用户不存在");
            return res;
        }
        if (!user.getPassword().equals(password)){
            res.put("code",102);
            res.put("masg","用户名或密码错误");
            return res;
        }

        if (user.getState()){
            res.put("code",103);
            res.put("masg","账户状态不可用");
            return res;
        }

        //TODO 从TokenUtil获取token，存到user表中，每次请求都带token，返回的时候更新一个新的token返回
        res.put("code",200);
        res.put("masg","登录成功");
        return res;

    }

    @Override
    public Map<String, Object> logout(Map<String, Object> map) {
        String code = "-1";
        Map<String,Object> res = new HashMap<>();
        String username = (String) map.get("username");

        User user = findByPhone(username);
        if (user == null){
            res.put("code",101);
            res.put("masg","用户不存在");
            return res;
        }

        //TODO 从TokenUtil获取token，存到user表中，每次请求都带token，返回的时候更新一个新的token返回
        res.put("code",200);
        res.put("masg","用户已退出");
        return res;
    }

    @Override
    public Map<String, Object> register(User user) {

        this.save(user);

        Map<String,Object> res = new HashMap<>();
        res.put("code",200);
        res.put("masg","注册成功");
        return res;
    }
}
